<template>
  <div class="space-y-4">
    <!-- 错误类别 -->
    <div 
      v-for="(errors, category) in categorizedErrors" 
      :key="category"
      class="bg-white rounded-lg shadow-sm overflow-hidden"
    >
      <!-- 类别标题（可折叠） -->
      <button
        @click="toggleCategory(category)"
        class="w-full px-6 py-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
      >
        <div class="flex items-center space-x-3">
          <component 
            :is="getCategoryIcon(category)" 
            class="w-5 h-5"
            :class="getCategoryColor(category)"
          />
          <span class="font-medium text-gray-900">
            {{ getCategoryName(category) }}
          </span>
          <span 
            class="px-2 py-1 text-xs rounded-full"
            :class="getCategoryBadgeClass(category)"
          >
            {{ errors.length }}个问题
          </span>
        </div>
        
        <ChevronDown 
          class="w-5 h-5 text-gray-400 transition-transform duration-200"
          :class="{ 'transform rotate-180': expandedCategories[category] }"
        />
      </button>
      
      <!-- 错误列表（可折叠） -->
      <transition
        name="expand"
        @enter="onEnter"
        @after-enter="onAfterEnter"
        @leave="onLeave"
      >
        <div v-show="expandedCategories[category]" class="border-t border-gray-100">
          <div class="px-6 py-4 space-y-3">
            <div 
              v-for="(error, index) in errors" 
              :key="index"
              class="relative p-4 rounded-lg border-l-4 transition-all duration-200 cursor-pointer"
              :class="getErrorCardClass(error.type)"
              @click="$emit('error-click', error)"
            >
              <!-- 错误位置 -->
              <div class="flex items-start justify-between mb-3">
                <span class="text-sm font-semibold" :class="getErrorLabelColor(error.type)">
                  {{ error.position || `第${index + 1}处` }}
                </span>
                <span 
                  class="px-2.5 py-1 text-xs font-medium rounded-full shadow-sm"
                  :class="getErrorTypeBadge(error.type)"
                >
                  {{ getErrorTypeName(error.type) }}
                </span>
              </div>
              
              <!-- 原文与建议 -->
              <div class="space-y-3">
                <div class="flex items-start space-x-2.5" v-if="error.original || error.original_text">
                  <div class="w-5 h-5 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0 mt-0.5">
                    <X class="w-3.5 h-3.5 text-red-600" />
                  </div>
                  <div class="flex-1">
                    <div class="text-xs font-medium text-gray-500 mb-1.5">原文</div>
                    <div class="text-sm bg-red-50 border border-red-200 rounded-md px-3 py-2 text-red-700 line-through">
                      {{ error.original || error.original_text || error.original_excerpt || '未提供原文' }}
                    </div>
                  </div>
                </div>
                
                <div class="flex items-start space-x-2.5" v-if="error.suggested || error.suggested_text || error.suggested_revision">
                  <div class="w-5 h-5 rounded-full bg-green-100 flex items-center justify-center flex-shrink-0 mt-0.5">
                    <Check class="w-3.5 h-3.5 text-green-600" />
                  </div>
                  <div class="flex-1">
                    <div class="text-xs font-medium text-gray-500 mb-1.5">修改建议</div>
                    <div class="text-sm bg-green-50 border border-green-200 rounded-md px-3 py-2 text-green-700 font-medium">
                      {{ error.suggested || error.suggested_text || error.suggested_revision || '未提供建议' }}
                    </div>
                  </div>
                </div>
                
                <!-- 如果既没有原文也没有建议，显示提示 -->
                <div v-if="!error.original && !error.original_text && !error.suggested && !error.suggested_text && !error.suggested_revision" class="text-sm text-gray-500 italic bg-gray-50 rounded-md p-3">
                  批注信息不完整，请重新提交批改
                </div>
              </div>
              
              <!-- 错误原因 -->
              <div v-if="error.reason" class="mt-3 pt-3 border-t-2 border-dashed" :class="getReasonBorderColor(error.type)">
                <div class="flex items-start space-x-2.5">
                  <AlertCircle class="w-4 h-4 flex-shrink-0 mt-0.5" :class="getReasonIconColor(error.type)" />
                  <p class="text-sm text-gray-700 leading-relaxed">{{ error.reason }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </transition>
    </div>
    
    <!-- 空状态 -->
    <div v-if="Object.keys(categorizedErrors).length === 0" class="text-center py-12">
      <CheckCircle class="w-16 h-16 text-green-500 mx-auto mb-4" />
      <p class="text-gray-600">没有发现任何错误，太棒了！</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { 
  ChevronDown, 
  AlertCircle, 
  Check, 
  X, 
  CheckCircle,
  FileText,
  Lightbulb,
  MessageSquare,
  Layout,
  Sparkles
} from 'lucide-vue-next';

/**
 * ErrorList 组件
 * 显示分类的错误列表，支持折叠/展开
 */

// ==================== Props ====================
const props = defineProps({
  /**
   * 错误列表
   * @type {Array<{ type: string, position: string, original: string, suggested: string, reason: string }>}
   */
  errors: {
    type: Array,
    default: () => [],
  },
});

// ==================== Emits ====================
const emit = defineEmits(['error-click']);

// ==================== Refs ====================
const expandedCategories = ref({});

// ==================== Computed ====================

/**
 * 按类别分组的错误
 */
const categorizedErrors = computed(() => {
  const categories = {};
  
  props.errors.forEach((error) => {
    const category = mapErrorCategory(error.type);
    if (!categories[category]) {
      categories[category] = [];
    }
    categories[category].push(error);
  });
  
  return categories;
});

// ==================== Methods ====================

/**
 * 映射错误类型到类别
 */
const mapErrorCategory = (type) => {
  const mapping = {
    'spelling': 'language',
    'grammar': 'language',
    'punctuation': 'language',
    'word_choice': 'language',
    'sentence_structure': 'structure',
    'paragraph_structure': 'structure',
    'logic': 'logic',
    'coherence': 'logic',
    'content': 'content',
    'theme': 'content',
    'detail': 'detail',
  };
  
  return mapping[type] || 'detail';
};

/**
 * 获取类别名称
 */
const getCategoryName = (category) => {
  const names = {
    'content': '内容问题',
    'logic': '逻辑问题',
    'language': '语言问题',
    'structure': '结构问题',
    'detail': '细节问题',
  };
  return names[category] || category;
};

/**
 * 获取类别图标
 */
const getCategoryIcon = (category) => {
  const icons = {
    'content': FileText,
    'logic': Lightbulb,
    'language': MessageSquare,
    'structure': Layout,
    'detail': Sparkles,
  };
  return icons[category] || AlertCircle;
};

/**
 * 获取类别颜色
 */
const getCategoryColor = (category) => {
  const colors = {
    'content': 'text-blue-500',
    'logic': 'text-purple-500',
    'language': 'text-red-500',
    'structure': 'text-amber-500',
    'detail': 'text-green-500',
  };
  return colors[category] || 'text-gray-500';
};

/**
 * 获取类别徽章样式
 */
const getCategoryBadgeClass = (category) => {
  const classes = {
    'content': 'bg-blue-100 text-blue-800',
    'logic': 'bg-purple-100 text-purple-800',
    'language': 'bg-red-100 text-red-800',
    'structure': 'bg-amber-100 text-amber-800',
    'detail': 'bg-green-100 text-green-800',
  };
  return classes[category] || 'bg-gray-100 text-gray-800';
};

/**
 * 获取错误类型名称
 */
const getErrorTypeName = (type) => {
  const names = {
    'spelling': '错别字',
    'grammar': '语法错误',
    'punctuation': '标点错误',
    'word_choice': '用词不当',
    'sentence_structure': '句式问题',
    'paragraph_structure': '段落结构',
    'logic': '逻辑问题',
    'coherence': '连贯性',
    'content': '内容问题',
    'theme': '主题问题',
    'detail': '细节问题',
  };
  return names[type] || type;
};

/**
 * 获取错误类型徽章样式
 */
const getErrorTypeBadge = (type) => {
  const category = mapErrorCategory(type);
  return getCategoryBadgeClass(category);
};

/**
 * 获取错误卡片样式（包含左边框颜色和背景色）
 */
const getErrorCardClass = (type) => {
  const category = mapErrorCategory(type);
  const classes = {
    'content': 'border-blue-500 bg-blue-50/30 hover:bg-blue-50/50 hover:shadow-md',
    'logic': 'border-purple-500 bg-purple-50/30 hover:bg-purple-50/50 hover:shadow-md',
    'language': 'border-red-500 bg-red-50/30 hover:bg-red-50/50 hover:shadow-md',
    'structure': 'border-amber-500 bg-amber-50/30 hover:bg-amber-50/50 hover:shadow-md',
    'detail': 'border-green-500 bg-green-50/30 hover:bg-green-50/50 hover:shadow-md',
  };
  return classes[category] || 'border-gray-400 bg-gray-50/30 hover:bg-gray-50/50 hover:shadow-md';
};

/**
 * 获取错误标签颜色
 */
const getErrorLabelColor = (type) => {
  const category = mapErrorCategory(type);
  const colors = {
    'content': 'text-blue-700',
    'logic': 'text-purple-700',
    'language': 'text-red-700',
    'structure': 'text-amber-700',
    'detail': 'text-green-700',
  };
  return colors[category] || 'text-gray-700';
};

/**
 * 获取原因边框颜色
 */
const getReasonBorderColor = (type) => {
  const category = mapErrorCategory(type);
  const colors = {
    'content': 'border-blue-200',
    'logic': 'border-purple-200',
    'language': 'border-red-200',
    'structure': 'border-amber-200',
    'detail': 'border-green-200',
  };
  return colors[category] || 'border-gray-200';
};

/**
 * 获取原因图标颜色
 */
const getReasonIconColor = (type) => {
  const category = mapErrorCategory(type);
  const colors = {
    'content': 'text-blue-600',
    'logic': 'text-purple-600',
    'language': 'text-red-600',
    'structure': 'text-amber-600',
    'detail': 'text-green-600',
  };
  return colors[category] || 'text-gray-600';
};

/**
 * 切换类别展开/折叠
 */
const toggleCategory = (category) => {
  expandedCategories.value[category] = !expandedCategories.value[category];
};

/**
 * 折叠动画 - 进入前
 */
const onEnter = (el) => {
  el.style.height = '0';
};

/**
 * 折叠动画 - 进入后
 */
const onAfterEnter = (el) => {
  el.style.height = 'auto';
};

/**
 * 折叠动画 - 离开
 */
const onLeave = (el) => {
  el.style.height = el.scrollHeight + 'px';
  el.offsetHeight; // force reflow
  el.style.height = '0';
};

// ==================== 初始化 ====================

// 默认展开所有类别
Object.keys(categorizedErrors.value).forEach((category) => {
  expandedCategories.value[category] = true;
});
</script>

<style scoped>
/* 折叠展开动画 */
.expand-enter-active,
.expand-leave-active {
  transition: height 0.3s ease;
  overflow: hidden;
}
</style>

